// subpkg/seat/seat.js
// import { getCinemaSeat } from '../../api/seat'
import { getCinemaSeat2 } from '../../api/seat'
const app = getApp()
Page({
  /**
   * 页面的初始数据
   */
  data: {
    cinemaSeat: {}, // 座位信息
    movieBuyInfo: {}, // 电影信息
    selectedSeatList: [], // 选中座位列表
    seatNoList: [],
    totalPrice: 0
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.setData({
      movieBuyInfo: app.globalData.movieBuyInfo
    })

    this.getCinemaSeatData()
  },
  // 获取电影院座位
  async getCinemaSeatData() {
    //  const res = await getCinemaSeat()
    const res = await getCinemaSeat2()

    this.setData({
      cinemaSeat: res.data
    })
  },
  // 选择座位
  selectSeat(e) {
    const { rowid, columnid, seatno } = e.target.dataset
    const findIndex = this.data.selectedSeatList.findIndex(item => item.seatno === seatno)
    if (findIndex > -1) {
      this.data.selectedSeatList.splice(findIndex, 1)
    } else {
      if (this.data.selectedSeatList.length >= 4) {
        wx.showToast({
          title: '一次最多购买4张票',
          icon: 'none',
          duration: 800
        })
        return
      }

      this.data.selectedSeatList.push({ rowid, columnid, seatno, price: this.data.movieBuyInfo.vipPrice })
    }

    this.updateSeatListAndPrice()
  },
  // 删除座位
  deleteSeat(e) {
    const findIndex = this.data.selectedSeatList.findIndex(item => item.seatno === e.target.dataset.seatno)
    if (findIndex > -1) {
      this.data.selectedSeatList.splice(findIndex, 1)

      this.updateSeatListAndPrice()
    }
  },
  updateSeatListAndPrice() {
    this.setData({
      selectedSeatList: this.data.selectedSeatList,
      seatNoList: this.data.selectedSeatList.map(item => item.seatno),
      totalPrice: this.data.selectedSeatList.reduce((total, item) => total + parseFloat(item.price), 0).toFixed(2)
    })
  },
  // 座位不可售
  noSale() {
    wx.showToast({
      title: '此座位不可售',
      icon: 'none',
      duration: 800
    })
  },
  goToOrder() {
    if (this.data.selectedSeatList.length === 0) return
    app.globalData.movieBuyInfo = {
      ...app.globalData.movieBuyInfo,
      count: this.data.selectedSeatList.length,
      seatList: this.data.selectedSeatList.map(item => {
        return `${item.rowid}排${item.columnid}座`
      }),
      totalPrice: this.data.totalPrice
    }

    wx.navigateTo({
      url: '/subpkg/order/order',
    })
  }
})